package cn.edu.scau.cmi.xiaozhenlin.hibernate;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Hibernate {
	static Connection conn;
	PreparedStatement ps;
	ResultSet rs;

	public Hibernate() {
		// TODO 自动生成的构造函数存根
		try {
			Class.forName("com.mysql.jdbc.Driver");
			System.out.println("成功加载sql驱动");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("找不到sql驱动");
			e.printStackTrace();
		}
		String url = "jdbc:mysql://localhost:3306/hibernate?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";

		try {
			conn = (Connection) DriverManager.getConnection(url, "root", "root");
			// 创建一个Statement对象
			Statement stmt = (Statement) conn.createStatement(); // 创建Statement对象
			System.out.print("成功连接到数据库！");
			ResultSet rs = stmt.executeQuery("select * from student");
			System.out.println(rs.toString());
			while (rs.next()) {
				System.out.println(rs.getString("name"));
			}
			stmt.close();
			// conn.close();
		} catch (SQLException e) {
			System.out.println("fail to connect the database!");
			e.printStackTrace();
		}
	}

	public void create(String id, String name) {

		try {
			ps = conn.prepareStatement("insert into student values(?,?)");
			ps.setString(1, id);
			ps.setString(2, name);
			ps.executeUpdate();
			ps.close();
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}

	public void delete(String id) {

		try {
			ps = conn.prepareStatement(" Delete From student Where id = " + id);
			ps.executeUpdate();
			ps.close();
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}

	}

	public String retrieve(String id) {
		Statement stmt;
		try {
			stmt = (Statement) conn.createStatement();
			ResultSet rs = stmt.executeQuery("select * from student where id = " + id);
			while (rs.next()) {
				return rs.getString("name");
			}
			stmt.close();
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} // 创建Statement对象
		return id;
	}

	public void update(String id, String name) {
		Statement stmt;
		ResultSet rs;
		try {
			stmt = (Statement) conn.createStatement();
			rs = stmt.executeQuery("select * from student where id = " + id);
			if (rs.next()) {
				rs.updateString(2, name);
				rs.updateRow();
			}

		} catch (SQLException e1) {
			// TODO 自动生成的 catch 块
			e1.printStackTrace();
		} // 获取数据表结果集

	}
}
